//
//  HigherOrderFunction.swift
//  functional
//
//  Created by LimitLiu on 2019/2/11.
//  Copyright © 2019 LimitLiu. All rights reserved.
//

import UIKit

class HigherOrderFunction: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        let xs = [1, 2, 3, 4]
        let texts = xs.genericArray { x in
            x * 2
        }
        for text in texts {
            let label = UILabel(frame: CGRect(x: 100, y: text * 35, width: 20, height: 30))
            label.text = String(text)
            view.addSubview(label)
        }
    }

}

func incrementArray(xs: [Int]) -> [Int] {
    return xs.genericArray { x in
        x + 1
    }
}

func doubleArray(xs: [Int]) -> [Int] {
    return xs.genericArray { x in
        x * 2
    }
}

func isEvenArray(xs: [Int]) -> [Bool] {
    return xs.genericArray { x in
        x % 2 == 0
    }
}

extension Array {
    func genericArray<T>(_ transform: (Element) -> T) -> [T] {
        var result:[T] = []
        for x in self {
            result.append(transform(x))
        }
        return result
    }
}
